package org.apache.rocketmq.common;

import org.apache.commons.lang3.StringUtils;
import org.apache.rocketmq.common.constant.LoggerName;
import org.apache.rocketmq.logging.org.slf4j.Logger;
import org.apache.rocketmq.logging.org.slf4j.LoggerFactory;

import java.net.InetAddress;
import java.net.UnknownHostException;

public class BrokerIdentity {
    private static final String DEFAULT_CLUSTER_NAME = "defaultCluster";

    protected static final Logger LOGGER = LoggerFactory.getLogger(LoggerName.COMMON_LOGGER_NAME);

    private static String localHostName;

    static {
        try {
            localHostName = InetAddress.getLocalHost().getHostName();
        } catch (UnknownHostException e) {
            LOGGER.error("Failed to obtain the host Name", e);
        }
    }

    private String brokerName = defaultBrokerName();

    private String brokerClusterName = DEFAULT_CLUSTER_NAME;

    private volatile long brokerId = MixAll.MASTER_ID;

    private boolean isInBrokerContainer = false;

    public BrokerIdentity() {
    }

    public BrokerIdentity(boolean isInBrokerContainer) {
        this.isInBrokerContainer = isInBrokerContainer;
    }

    public boolean isInBrokerContainer() {
        return isInBrokerContainer;
    }

    public String getCanonicalName() {
        return isInBrokerContainer ? "BrokerContainer" : String.format("%s_%s_%d", brokerClusterName, brokerName,
                brokerId);
    }

    public String defaultBrokerName() {
        return StringUtils.isEmpty(localHostName) ? "DEFAULT_BROKER" : localHostName;
    }

}
